# -*- coding: utf-8 -*-
import logging
from pathlib import Path

from config import base_config

def info_filter(record):
    return record.levelno == logging.INFO

def warn_filter(record):
    return record.levelno == logging.WARNING

def error_filter(record):
    return record.levelno == logging.ERROR

def generate_logger(info_log_path, warn_log_path, error_log_path):
    for _path in [info_log_path, warn_log_path, error_log_path]:
        file_path = Path(_path)
        directory = file_path.parent
        if not directory.exists():
            directory.mkdir(parents=True, exist_ok=True)
        if not file_path.exists():
            file_path.touch()

    log_files = {
        "info": info_log_path,
        "warn": warn_log_path,
        "error": error_log_path,
    }

    handlers = {
        "info": logging.FileHandler(log_files["info"]),
        "warn": logging.FileHandler(log_files["warn"]),
        "error": logging.FileHandler(log_files["error"]),
    }

    for handler_name, handler in handlers.items():
        if handler_name == "info":
            handler.addFilter(info_filter)
        elif handler_name == "warn":
            handler.addFilter(warn_filter)
        elif handler_name == "error":
            handler.addFilter(error_filter)
        else:
            pass

        formatter = logging.Formatter(
            "%(asctime)s [%(levelname)s] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)

    logger = logging.getLogger("Sanic")
    logger.setLevel(logging.DEBUG)

    for existing_handler in logger.handlers[:]:
        logger.removeHandler(existing_handler)

    for handler in handlers.values():
        logger.addHandler(handler)

    return logger


logger = generate_logger(base_config.INFO_LOG_PATH, base_config.WARN_LOG_PATH, base_config.ERROR_LOG_PATH)
